#!/usr/bin/env bash
set -e

sshdir=$HOME/.ssh
knownhosts=$sshdir/known_hosts
authorizedkeys=$sshdir/authorized_keys

sshkey () {
    [ ! -e ${sshdir} ] && mkdir ${sshdir}
    [ -z "$*" ] && return -1
    
    ssh-keyscan $* 2>/dev/null | while read pubkey
    do
        [ "${pubkey:0:1}" != "#" ] && {
            keyparts=($pubkey)
            [ "${keyparts[1]}" == "ssh-rsa" ] && {
                # echo ${keyparts[1]} ${keyparts[2]}
                echo "${keyparts[1]} ${keyparts[2]}">>$knownhosts
                echo "${keyparts[1]} ${keyparts[2]}">>$authorizedkeys
                echo "public key of ${keyparts[0]} has been added to trust host list."
            }
        }
    done
}

sshkey $*